<?php if ( ! defined('APPPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
class social_controller extends PZ_Controller{

	public function __construct() {
		parent::__construct();
		$this->authfunctions = array('unbind');
	}

	protected function init(){
		$this->session = &load_class('Session');
	}

	public function go(){
		$vendor = $this->param("vendor");
		$connector = load_api('social/'.$vendor);
		$url = $connector->getloginpage();
		$this->jump($url);
	}

	public function callback()
	{
		$vendor = $this->param("vendor");
		$connector = load_api('social/'.$vendor);
		if($token = $connector->get_accesstoken($vendor)){
			if($userinfo = $connector->get_userinfo($vendor)){
				$userinfo['vendor'] = $vendor;
				$this->session->put('social_info',$userinfo);
				$this->session->put('social_'.$vendor.'_info',$token);
				$this->social_info = $userinfo;
				$this->bind();
				return;
			}
		}
		$this->message(lang('error','tip'), 'Social login callback error token='.$token);
	}
	public function unbind(){
		$connectdb = load_db('social/connector');
		$vendor = $this->param("vendor");
		$connectdb->del_connector_by_vendor_uid($vendor,$this->cuser['uid']);
		$this->redirect(site_url('home/bindsetting'), lang('200_operatesuccess','tip'));
	}

	public function bind(){
		$connectdb = load_db('social/connector');
		$userdb = load_db('user');
		$userapi = load_api("user");
		if($this->social_info){
			$social_user_info = $this->social_info;
		}else{
			$social_user_info = $this->session->get('social_info');
		}
		$vendor = $social_user_info['vendor'];
		if(!$vendor){
			$this->message(lang('error','tip'), "Failed to get your {$vendor} account info! ");
			return;
		}
		if($nickname = $this->param("nickname")){
			if($userdb->checknick($nickname)){
				load_helper('string');
				
				if($social_user_info['email']&&($user = $userapi->getUserByEmail($social_user_info['email']))){
					$uid = $user['user_id'];
					$data=$user;
				}else{
					$data['email'] = $social_user_info['email']?$social_user_info['email']:md5(random_string('alnum', 5)).'@'.config_item('default_domain');
					$data['nickname'] = $nickname;
					//$data['avatar_remote'] = $social_user_info['avatar'];
					$data['gender'] = $social_user_info['gender'];
					$data['location'] = $social_user_info['location'];
					$data['bio'] = $social_user_info['description'];
					$password = random_string('alnum', 8);
					$data['passwd'] = md5($password);
					$data['create_time'] = TIMESTAMP;
					$data['is_social'] = 1;
					$uid = $userdb->add_one($data);
					$data['password'] = $password;
				}
				

				$connector_data['user_id'] = $uid;
				$connector_data['social_userid'] = $social_user_info['uid'];
				$connector_data['vendor'] = $vendor;
				$connector_data['vendor_info'] = serialize($this->session->get('social_'.$vendor.'_info'));
				$connector_data['username'] = $social_user_info['screen_name'];
				$connector_data['name'] = $social_user_info['name'];
				$connector_data['description'] = $social_user_info['description'];
				$connector_data['homepage'] = $social_user_info['url'];
				$connector_data['avatar'] = $social_user_info['avatar'];
				$connector_data['email'] = $social_user_info['email'];
				$connector_data['gender'] = $social_user_info['gender'];
				$connector_data['location'] = $social_user_info['location'];
				$connectdb->create($connector_data);

				$this->save_remote_avatar($social_user_info['avatar'], $uid);
				load_api('event')->register($uid,true);
				$data['remember'] = true;
				$userapi->setsession($data);
				$this->clear_socialinfo($vendor);
				$this->ajax_success_response(array('url'=>site_url(config_item('default_module'))), lang('200_registersuccess','tip'));
				return;
			}else{
				$this->ajax_failed_response(lang('500_nickname_existed','tip'));
			}
		}else{
			$social_connector = $connectdb->get_bind_by_vendor_and_suid($vendor,$social_user_info['uid']);
			if($social_connector){
				if($this->cuser['uid']&&$social_connector['user_id']!=$this->cuser['uid']){
					$this->redirect(site_url('home/bindsetting'), lang('account_already_bind','social'),8);
					return;
				}else{
					$update_connect_data['avatar'] = $social_user_info['avatar'];
					//$update_local_data['avatar_remote'] = $social_user_info['avatar'];
					//need update remote avatar
					$connectdb->update(array('connect_id'=>$social_connector['connect_id']),$update_connect_data);
					//$this->user_model->edit_user($social_connector['user_id'],$update_local_data);

					$local_user = $userapi->getUserByid($social_connector['user_id']);
					$userapi->setsession($local_user);
					$this->clear_socialinfo($vendor);
					$this->redirect(site_url('home/bindsetting'), lang('200_operatesuccess','tip'));
				}
			}else{
				if($this->islogin){
					$connector_data['user_id'] = $this->cuser['uid'];
					$connector_data['social_userid'] = $social_user_info['uid'];
					$connector_data['vendor'] = $vendor;
					$connector_data['vendor_info'] = serialize($this->session->get('social_'.$vendor.'_info'));
					$connector_data['username'] = $social_user_info['screen_name'];
					$connector_data['name'] = $social_user_info['name'];
					$connector_data['description'] = $social_user_info['description'];
					$connector_data['homepage'] = $social_user_info['url'];
					$connector_data['avatar'] = $social_user_info['avatar'];
					$connector_data['email'] = $social_user_info['email'];
					$connector_data['gender'] = $social_user_info['gender'];
					$connector_data['location'] = $social_user_info['location'];
					$connectdb->create($connector_data);
					$this->redirect(site_url('home/bindsetting'), lang('200_operatesuccess','tip'));
				}else{
					$this->social_user_info = $social_user_info;
					$this->output("user/socialinfo");
				}
			}
		}
	}

	private function save_remote_avatar($url,$uid){
		$content = get_contents($url);
		$ptx_user = load_db('user');
		$avaorgin = useravatarpath($uid,false);
		$avalarge = useravatarpath($uid,'large');
		$avamiddle = useravatarpath($uid,'middle');
		$avasmall = useravatarpath($uid,'small');
		$avatardir = BASEPATH.useravatardir($uid);
		(!is_dir($avatardir))&&@mkdir($avatardir,0777,true);
		file_exists(BASEPATH.$avaorgin) && unlink(BASEPATH.$avaorgin);
		file_exists(BASEPATH.$avalarge) && unlink(BASEPATH.$avalarge);
		file_exists(BASEPATH.$avamiddle) && unlink(BASEPATH.$avamiddle);
		file_exists(BASEPATH.$avasmall) && unlink(BASEPATH.$avasmall);

		$imagepath = BASEPATH.$avaorgin;
		if(!empty($content) && @file_put_contents($imagepath,$content) > 0){
			$imagelib =  &load_class('ImageLib');
			$imagelib->create_thumb($imagepath,NULL,150,150,BASEPATH.$avalarge);
			$imagelib->create_thumb($imagepath,NULL,50,50,BASEPATH.$avamiddle);
			$imagelib->create_thumb($imagepath,NULL,16,16,BASEPATH.$avasmall);
			return true;
		}else{
			load_helper('view');
			create_default_avatar($user_id);
			return true;
		}
		return false;
	}

	private function clear_socialinfo($vendor){
		$this->session->put('social_info','');
	}

}
